package org.shj.thread.book2.chapter06.improve;

import java.util.concurrent.BrokenBarrierException;
import java.util.concurrent.CyclicBarrier;

public class WriterThread extends Thread{
	
	private final Data data;
	private final String filler;
	private int index = 0;
	private CyclicBarrier barrier;
	
	public WriterThread(Data data, CyclicBarrier barrier, String filler){
		this.data = data;
		this.filler = filler;
		this.barrier = barrier;
	}
	
	public WriterThread(Data data, String filler){
		this.data = data;
		this.filler = filler;
	}
	
	public void run(){
		try{
			//for(int i = 0 ; i < 10; i++){
			for(; index < filler.length(); index++){
				char c = filler.charAt(index);
				data.write(c);
				//Thread.sleep(10);
			}
			//}
			barrier.await();
			
		}catch(InterruptedException e){
			
		}catch(BrokenBarrierException be){
			
		}
	}
	
	/*public void run(){
		try{
			while(true){
				char c = nextchar();
				data.write(c);
				//Thread.sleep(random.nextInt(3000));
			}
		}catch(InterruptedException e){
			
		}
	}
	
	private char nextchar(){
		char c = filler.charAt(index);
		index++;
		if(index >= filler.length()){
			index = 0;
		}
		
		return c;
	}*/
}
